<template>
  <div class="the-map-component">
    <v-stage ref="ref-stage" :config="stageConfig">
      <v-layer>
        <v-image
          :config="{
          image:mapImage,
          width:mapSize,
          height:mapSize
        }"
        ></v-image>
        <!-- <v-rect
          :config="{
          x: 0,
          y: 0,
          width: 100,
          height: 100,
          fill: 'red',
          shadowBlur: 10
        }"
        />-->
      </v-layer>
      <v-layer ref="lines-layer"></v-layer>
    </v-stage>
  </div>
</template>

<script>
import axios from "axios";
import konva from "konva";
import { map, clamp, sortBy } from "lodash";

// const KonvaLayer = konva.Layer;

const TestMatchId =
  "match.bro.official.pc-2018-06.steam.squad.na.2020.02.08.12.5275ac61-d5ec-46d9-a910-ca37c1ef3938";
const Characters_5275ac61d5ec46d9a910ca37c1ef3938 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/A2/9B/Cii-U16cReeIZHe_ALD-IcFeeLoAAMXpQDDXBoAsP4570.json";
const MatchInfo_5275ac61d5ec46d9a910ca37c1ef3938 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/A2/9B/Cii-TF6cRjOIf-JjAAAnfLXPGOgAAMXpQGHwkAAACeU94.json";
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "http://p1-q.mafengwo.net/s16/M00/25/2E/CoUBUl6J8HWAB3mbABe2H5mDyy8107.jpg#Savage_Main.jpg.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};

const MAP_NAME = "Miramar";

let match_id =
  "match.bro.official.pc-2018-06.steam.squad.na.2020.02.08.12.5275ac61-d5ec-46d9-a910-ca37c1ef3938";

const toScale = (pubgMapSize, mapSize, n) =>
  (n / pubgMapSize) * mapSize * (pubgMapSize === 816000 ? 0.99609375 : 1);

const DRAW_MAP_SIZE = 800;
export default {
  name: "HelloWorld",
  data() {
    return {
      mapSize: DRAW_MAP_SIZE,
      stageConfig: {
        width: DRAW_MAP_SIZE,
        height: DRAW_MAP_SIZE,
        draggable: true
      },
      mapName: MAP_NAME,
      mapImageLink: MAP_IMAGES[MAP_NAME],
      mapImage: (_ => {
        let img = new window.Image();
        img.src = MAP_IMAGES[MAP_NAME];
        return img;
      })(),
      mapScale: 1,
      offsetX: 0,
      offsetY: 0
    };
  },
  computed: {},
  async mounted() {
    let o_matchInfo = await this.getMatchInfo();
    let o_charas = await this.getCharactersData();
    // debugger
    let v_layer = this.$refs["lines-layer"];
    /**@type {konva.Layer} */
    let layer = v_layer.getNode();

    let characters_coords = (_ => {
      let s = o_charas.map(e => {
        // debugger;
        let points = e.arrayOfCharacters.map(c => {
          return [c.character.location.x, c.character.location.y];
        });
        let mapSize = DRAW_MAP_SIZE;
        let rawMapSize = MAP_LENGTH_CENTIMETERS[MAP_NAME];
        let _scale = mapSize / rawMapSize;
        points = points.map(p => {
          return [p[0] * _scale, p[1] * _scale];
        });
        return points;
      });
      return s;
    })();
    let k_lines = characters_coords.map(ps => {
      if (ps.length >= 2) {
        let line = new konva.Line({
          points: ps.reduce((a, b) => a.concat(b)),
          stroke: "white",
          strokeWidth: 2,
          lineCap: "round",
          lineJoin: "round",
          opacity: 0.5
        });
        return line;
      } else {
        return null;
      }
    });
    k_lines = k_lines.filter(e => !!e);
    layer.add(...k_lines);
    // layer.add(
    //   new konva.Rect({
    //     x:0,
    //     // x: 0,
    //     y: 0,
    //     width: 100,
    //     height: 100,
    //     fill: "red",
    //     shadowBlur: 10
    //   })
    // );
    let tooltip = new konva.Label({
      x: 150,
      y: 250
    });
    tooltip.add(
      new konva.Tag({
        fill: "black",
        pointerDirection: "down",
        pointerWidth: 10,
        pointerHeight: 10
      })
    );
    tooltip.add(
      new konva.Text({
        text: "标记A",
        fill: "white",
        padding:5
      })
    );
    layer.add(tooltip);
    layer.draw();
    setInterval(()=>{
      tooltip.x(tooltip.x()+1);
      tooltip.y(tooltip.y()+1);
      layer.draw();
    },100)
    const MIN_SCALE = 1;
    const MAX_SCALE = 50;
    let v_stage = this.$refs["ref-stage"];
    /**@type {konva.Stage} */
    let stage = v_stage.getNode();
    let v = this;

    let handleZoom =
      /**
       * @param {Number} scaleDelta
       * @param {Number} layerX?
       * @param {Number} layerY?
       */
      (scaleDelta, layerX, layerY) => {
        if (!layerX) layerX = DRAW_MAP_SIZE / 2;
        if (!layerY) layerY = DRAW_MAP_SIZE / 2;
        let newScale = clamp(v.mapScale * scaleDelta, MIN_SCALE, MAX_SCALE);
        let mousePointX = layerX / v.mapScale - v.offsetX / v.mapScale;
        let mousePointY = layerY / v.mapScale - v.offsetY / v.mapScale;
        let offsetX = -(mousePointX - layerX / newScale) * newScale;
        let offsetY = -(mousePointY - layerY / newScale) * newScale;
        offsetX = clamp(offsetX, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        offsetY = clamp(offsetY, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        // debugger
        v.mapScale = newScale;
        v.offsetX = offsetX;
        v.offsetY = offsetY;
        // debugger;
        stage.scaleX(newScale);
        stage.scaleY(newScale);
        stage.x(offsetX);
        stage.y(offsetY);
        stage.batchDraw();
      };
    stage.dragBoundFunc(pos => {
      // debugger;
      let { x, y } = pos;
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      return {
        x,
        y
      };
    });
    stage.on("dragend", ev => {
      // debugger
      let x = ev.target.x();
      let y = ev.target.y();
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      stage.x(x);
      stage.y(y);
      stage.batchDraw();
    });
    stage.on("wheel", ev => {
      console.log(ev);
      ev.evt.preventDefault();
      const scaleDelta = ev.evt.deltaY > 0 ? 1 / 1.2 : 1.2;
      handleZoom(scaleDelta, ev.evt.layerX, ev.evt.layerY);
    });
    // debugger;
  },
  methods: {
    getCharactersData: function() {
      return new Promise(resolve => {
        axios
          .get(Characters_5275ac61d5ec46d9a910ca37c1ef3938)
          // .get(`http://localhost:3000/api/characters/${match_id}`)
          .then(axresp => {
            // debugger
            // this.character_datas = axresp.data;
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    getMatchInfo: function() {
      return new Promise(resolve => {
        axios
          .get(MatchInfo_5275ac61d5ec46d9a910ca37c1ef3938)
          // .get(`http://localhost:3000/api/match/${match_id}`)
          .then(axresp => {
            // this.match_info = axresp.data;
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@mapSize: 800px;
.the-map-component {
  display: flex;
  #map {
    width: @mapSize;
    height: @mapSize;
  }
  .h-check-players {
  }
}
</style>
